<?php
declare (strict_types = 1);

namespace app\common\controller;

use app\admin\service\AdminRomService;
use think\facade\Db;
use think\facade\View;
use think\helper\Str;

/**
 * 系统中台控制器基类
 * @author 贾二小
 * @since 2021/3/27
 */
class Backend extends CommonBase
{
    // 校验
    protected $config;

    public function initialize()
    {
        parent::initialize();
        //初始化配置
        self::initConfig();
    }

    /**
     * 配置参数
     * @author 贾二小
     * @since 2021/7/4
     */
    public function initConfig()
    {
        if(IS_GET){
            // 系统全称
            View::assign("siteName", get_config('site_name'));
            // 系统简称
            View::assign("nickName", get_config('nick_name'));
            // 系统版本
            View::assign("version", get_config('version'));
            // 静态资源存储位置
            View::assign("ctxPath", get_config('ctx_path'));
            //应用名
            View::assign("app", APP_NAME);
            //控制器名
            View::assign("con", CONTROLLER_NAME);
            //操作方法名
            View::assign("act", ACTION_NAME);
        }
    }

    /**
     * 空操作
     * @author 贾二小
     * @since 2021/3/28
     */
    public function __call($method, $args)
    {
        return view("public/404");
    }

    /**
     * 主页面
     * @author 贾二小
     * @since 2021/6/21
     */
    public function index(){
        return view();
    }

    /**
     * 表单页面
     * @author 贾二小
     * @since 2021/6/21
     */
    public function form(){
        return view();

    }

    /**
     * 列表数据
     * @author 贾二小
     * @since 2021/7/4
     */
    public function page(){
        //获取配置参数
        $config = $this->config;
        //表
        $table = empty($config['search_table']) ? Db::name($config['table_name'])->alias($config['table_alias']) : $config['search_table'];
        //显示字段
        $field = empty($config['search_field']) ? $config['table_alias'] : $config['search_field'];
        //Where条件
        $map = [];
        foreach ($config['search_param'] as $vo){
            $param_field = strpos($vo['field'], '.') ? $vo['field'] : $config['table_alias'].'.'.$vo['field'];
            $op = isset($vo['type']) ? $vo['type'] : '=';
            $param = isset($vo['param']) ? $vo['param'] : $vo['field'];
            switch ($op)
            {
                case '=':
                case '>':
                case '<':
                case '>=':
                case '<=':
                case '<>':
                    $val = input($param,null);
                    if(!empty($val)){
                        $map[] = [$param_field,$op,$val];
                    }
                    break;
                case 'like':;
                    $val = input($param,null);
                    if(!empty($val)){
                        $map[] = [$param_field,'like','%'.$val.'%'];
                    }
                    break;
                case 'like_later':
                    $val = input($param,null);
                    if(!empty($val)){
                        $map[] = [$param_field,'like','%'.$val];
                    }
                    break;
                case 'like_front':
                    $val = input($param,null);
                    if(!empty($val)){
                        $map[] = [$param_field,'like',$val.'%'];
                    }
                    break;
                case 'between':
                    $start_val = input($param[0],null);
                    $end_val = input($param[1],null);
                    if(!empty($start_val)&&!empty($end_val)){
                        $end_val = datetime($end_val,'Y-m-d 23:59:59');
                        $map[] =[$param_field, $op,[$start_val, $end_val]];
                    }else if(!empty($start_val)){
                        $map[] =[ $param_field, '>=', $start_val];
                    }else if(!empty($end_val)){
                        $end_val = datetime($end_val,'Y-m-d 23:59:59');
                        $map[] =[$param_field, '<=', $end_val];
                    }
                    break;
                case 'in':
                    //todo
                    break;
            }
        }
        //是否假删除
        if($config['is_delete']){
            $map[] = [$config['table_alias'].'.'.'is_delete','=',0];
        }
        //用户ID转姓名+驼峰法命名
        $user_id_name = get_user_id_name();
        $dataCamelCase = function ($item) use ($user_id_name) {
            if(isset($item['create_user_id']) && !empty($item['create_user_id'])){
                $item['create_user_name'] = $user_id_name[$item['create_user_id']];
            }
            if(isset($item['update_user_id']) && !empty($item['update_user_id'])){
                $item['update_user_name'] = $user_id_name[$item['update_user_id']];
            }
            return to_camel($item);
        };
        if($config['is_limit']){
            //分页
            $limit = input('limit/d',15);
            $page = input('page/d',1);
            //排序
            $sort = input("sortBy",'id');
            $order = input("orderBy",'desc');
            //查询数据
            $count = (clone $table)->where($map)->count();
            $list = $table->field($field)->where($map)->order($sort,$order)->page($page,$limit)->select()->map($dataCamelCase);
        }else{
            //查询数据
            $list = $table->field($field)->where($map)->select()->map($dataCamelCase);
            //查询数据
            $count = count($list);
        }
        $data = ['data'=>$list, 'count'=>$count];
        //返回数据
        $this->success($data, 0);
    }

    /**
     * 保存/新增 详情数据
     * @author 贾二小
     * @since 2021/7/4
     */
    public function save()
    {
        //获取配置参数
        $config = $this->config;
        //获取POST提交的参数
        $form = empty($config['search_field']) ? $config['table_alias'] : $config['form_field'];
        $data = $this->request->post(explode(",", $form));
        //数据验证
        $this->form_validated('form_validated1');
        //数据重复验证
        if(!empty($config['form_validated2'])){
            $map = [];
            foreach ($config['form_validated2'] as $vo){
                $map[] = [$vo,'=',$data[$vo]];
            }
            //是否假删除
            if($config['is_delete']){
                $map[] = ['is_delete','=',0];
            }
            if(isset($data['id']) && intval($data['id']) > 0){
                $map[] = ['id','<>',$data['id']];
            }
            $count = Db::name($config['table_name'])->where($map)->count();
            if ($count > 0) {
                $this->error('数据重复');
            }
        }
        //驼峰转下划线
        $data = to_snake($data);
        //数据保存
        if (isset($data['id']) && intval($data['id']) == 0) {
            unset($data['id']);
            $data['create_user_id'] = _current_user('id');
            $id = Db::name($config['table_name'])->insertGetId($data);
            $data['id'] = $id;
            //日志名称
            $this->sLog($config['name'].'_新增',"成功新增了1条数据");
        } else {
            $data['update_user_id'] = _current_user('id');
            Db::name($config['table_name'])->where(['id' => $data['id']])->update($data);
            //日志名称
            $this->sLog($config['name'].'_编辑',"成功编辑了1条数据");
        }
        //返回
        $this->success();
    }

    /**
     * 单据假删除
     * @author 贾二小
     * @since 2021/7/4
     */
    public function delete()
    {
        //获取配置参数
        $config = $this->config;
        $id = input('id');
        //数据验证
        if (empty($id)) {
            $this->error('ID接收异常');
        }
        $map = [];
        if(is_array($id)){
            $map[] = ['id','in',$id];
        }else{
            $map[] = ['id','=',$id];
        }
        if($config['is_delete']){
            $map[] = ['is_delete','=',0];
            $data = [];
            $data['update_user_id'] = _current_user('id');
            $data['is_delete'] = 1;
            $count = Db::name($config['table_name'])->where($map)->update($data);
        }else{
            $count = Db::name($config['table_name'])->where($map)->delete();
        }
        //日志名称
        $this->sLog($config['name'].'_删除',"成功删除了{$count}条数据");
        $this->success();
    }

    /**
     * 数据验证
     * @author 贾二小
     * @since 2021/7/4
     */
    function form_validated($validated)
    {
        //获取配置参数
        $config = $this->config;
        //数据验证
        foreach ($config[$validated] as $key=>$vo){
            $val = input($key);
            //空验证
            if(empty($val)){
                $this->error($vo['msg']);
            }
            //正则验证
            if(isset($vo['regex']) && $vo['regex'] && !preg_match($vo['pcre'], $val)){
                $this->error($vo['regex_msg']);
            }
            //数据库验证
            if(isset($vo['db']) && $vo['db']){
                $map = [];
                $map[$key] = $val;
                //是否假删除
                if($config['is_delete']){
                    $map['is_delete'] = 0;
                }
                $count = Db::name($config['table_name'])->where($map)->count();
                if($count === 0){
                    $this->error($vo['db_msg']);
                }
            }
        }
    }

}